import React, {
    Component,
} from 'react'
import { connect } from 'react-redux';
import { View, Text, Image, StyleSheet, TextInput, TouchableOpacity, Keyboard } from 'react-native'
import { SafeAreaView } from 'react-navigation'
import { NavigationHeader } from '../../components';
import { Px } from '../../utils'
import { SimpleItemsDialog } from 'react-native-pickers'
import { AssetImages, ActionTypes } from '../../constants'
const ImagePicker = require('react-native-image-picker');

// More info on all the options is below in the README...just some common use cases shown here
const options = {
    title: 'Select Avatar',
    customButtons: [
        { 
            name: 'fb',
            title: 'Choose Photo from Facebook'
        },
    ],
    storageOptions: {
        skipBackup: true,
        path: 'images'
    }
};

class PersonMessage extends Component {

    static propTypes = {
        
    };

    // 生命周期
    constructor(props) {
        super(props)
        this.state = {
            isEdit: false,
            username:'测试',
            image: '',
            gender: 0,
            name: ''
        }
    }

    componentWillMount() {
        const { user } = this.props.navigation.state.params || {}
        const {
            username,
            image,
            gender,
            name
        } = user
        this.setState({
            username: username,
            image: image,
            gender: gender,
            name: name
        })
    }

    // render part
    render() {
        const {
            gender,
            image,// 头像
            name// Nickname
        } = this.props.user
        console.log('personmessage', this.props)
        return (
            <SafeAreaView style={styles.contain}>
                <NavigationHeader
                    title="个人资料"
                    rightButton={this._renderRightButton()}
                    navigation={this.props.navigation}
                />
                <TouchableOpacity
                    activeOpacity={1}
                    onPress={() => {
                        Keyboard.dismiss()
                    }}
                    style={styles.container}>
                    <View style={{
                        height: Px(280),
                        width: '100%',
                        alignItems: 'center',
                        justifyContent: 'center'
                    }}>
                        <TouchableOpacity
                            onPress={() => {
                                this._showImageSelect()
                            }}
                        >
                            {this._renderHeadImage(this.state.image)}
                        </TouchableOpacity>
                    </View>
                    <View style={styles.listItem}>
                        <View style={styles.textView}>
                            <Text>姓名</Text>
                        </View>
                        <TextInput
                            editable={this.state.isEdit}
                            placeholder="请输入姓名"
                            style={styles.inputStyle}
                            value={this.state.name}
                            onChangeText={(text) => {
                                this.setState({
                                    name: text
                                })
                            }}
                        />
                    </View>
                    <View style={styles.listItem}>
                        <View style={styles.textView}>
                            <Text>性别</Text>
                        </View>
                        <TouchableOpacity
                            onPress={() => {
                                this.SimpleItemsDialog.show()
                                Keyboard.dismiss()
                            }}
                            disabled={!this.state.isEdit}
                            style={{ width: '100%' }}>
                            <Text style={{width: '100%', marginLeft: Px(16)}}>{this.state.gender == 0 ? '男': '女'}</Text>
                        </TouchableOpacity>
                    </View>
                    <SimpleItemsDialog
                        items={[{ value: 0, label: '男' }, { value: 1, label: '女' } ]}
                        itemKey='label'
                        ref={ref => this.SimpleItemsDialog = ref}
                        onPress={(value) => {
                            this.setState({
                                gender: value
                            })
                        }} />
                </TouchableOpacity>
            </SafeAreaView>
        )
    }

    _renderRightButton() {
        return (
            <TouchableOpacity
                style={{alignItems: 'flex-end'}}
                onPress={() => {
                    if (this.state.isEdit) {
                        // 更新
                        this._fetchUpdatePersonalMessage()
                    }
                    this.setState({
                        isEdit: !this.state.isEdit
                    })
                }}
            >
                <Text>{this.state.isEdit ? '更新': '编辑'}</Text>
            </TouchableOpacity>
        )
    }

    _renderHeadImage(url) {
        if (url.length === 0) {
            return (
                <Image
                    style={{width: Px(220), height: Px(220)}}
                    source={AssetImages.DEFAULT_FACE_IMAGE}
                />
            )
        } else {
            return (
                <Image
                    style={{ width: Px(220), height: Px(220), borderRadius: Px(110) }}
                    source={{uri: url}}
                />
            )
        }
    }

    _showImageSelect() {
        ImagePicker.showImagePicker(options, (response) => {
            console.log('Response = ', response);

            if (response.didCancel) {
                console.log('User cancelled image picker');
            }
            else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
            }
            else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
            }
            else {
                let source = { uri: response.uri };
                
                const { user } = this.props
                console.log('source', source, user);
                this.setState({
                    image: source.uri
                })
                const headData = {
                    uid: user.id,
                    type: 1,
                    upload: source.uri
                }
                actionUtil(ActionTypes.API_CHANGE_HEAD_IMAGE, { data: headData })
                // You can also display the image using data:
                // let source = { uri: 'data:image/jpeg;base64,' + response.data };

                // this.setState({
                //     avatarSource: source
                // });
            }
        });
    }

    _fetchUpdatePersonalMessage() {
        console.log('begin update')
        // API接口：http://eevee.petpika.cn/user/update
        // 输入变量：id（用户ID），name（用户昵称），gender（用户性别），profile（用户标签），
        // image（用户头像url），background（用户背景图url）
        // 示例：http://eevee.petpika.cn/user/update?id=2&name=xiaoyang&gender=0&profile=test&image=image_url&background=back_url
        const { id } = this.props.user
        const data = {
            id: id,
            name: this.state.name,
            gender: this.state.gender,
        }
        const callBack = this._finishChangeUserInfo.bind(this, data)
        actionUtil(ActionTypes.API_CHANGE_USER_INFO, { data, callBack })
    }

    _finishChangeUserInfo(data, response, error) {
        console.log('_finishChangeUserInfo', data)
        if (error) {
            return;
        }
        const { name, gender } = data;
        actionUtil(ActionTypes.API_UPDATE_USER_INFO, { name, gender })
    }
}

const styles = StyleSheet.create({
    contain: {
        flex: 1,
        backgroundColor: '#fff'
    },
    container: {
        flex: 1,
        backgroundColor: '#EFEFF4'
    },
    listItem: {
        flexDirection: 'row',
        paddingHorizontal: Px(30),
        height: Px(55),
        alignItems: 'center',
        backgroundColor: '#fff',
        marginTop: Px(8)
    },
    textView: {
        width: Px(100),
        alignItems:'center',
        justifyContent: 'center'
    },
    inputStyle: {
        marginLeft: Px(16)
    }
})

export default connect(state => ({
    user: state.user.user
})
)(PersonMessage)